<template>
  <div v-loading="mainLoading" class="app-container message-container">
    <div>
      <el-form
        ref="search"
        :inline="true"
        :model="searchForm"
      >
        <el-form-item prop="name" label="角色名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入角色名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="getTableList(false)"
          >
            查询
          </el-button>
          <el-button
            type="primary"
            @click="resetForm('search')"
          >
            重置
          </el-button>
        </el-form-item>
        <div class="btn-right-container">
          <el-button-group id="btnlist">
            <template v-if="btnPermission.length">
              <el-button v-for="item in btnLists" :key="item.funCode" v-permission="[item.funCode, btnPermission]" :type="item.color?item.color:'info'" :icon="'el-icon-'+(item.icon?item.icon:'setting')" size="medium" @click="handle(item.color ? item.funCode : '')">
                {{ item.funName }}
              </el-button>
            </template>
            <el-button size="medium" type="primary" @click="exportList">
              导出
            </el-button>
          </el-button-group>
        </div>
      </el-form>
      <el-table
        ref="singleTable"
        v-loading="tableLoading"
        :data="tableData"
        :border="true"
        highlight-current-row
        style="width: 100%; min-height: 620px;"
        max-height="620px"
        @row-click="handleClickRow"
      >
        <el-table-column label=" " width="55">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.checked" @click.native.stop="handleReturn(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column
          :index="indexMethod"
          type="index"
          label="序号"
          align="center"
          width="80"
        />
        <el-table-column
          prop="name"
          label="角色名称"
          align="center"
        />
        <el-table-column
          prop="permission"
          label="权限(key)"
          align="center"
        />
        <el-table-column
          prop="dataScope"
          label="角色领域"
          align="center"
        />
        <el-table-column
          prop="levelStr"
          label="角色级别"
          align="center"
        />
        <el-table-column
          label="操作"
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="viewDetail(scope.row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="_pagination-t15">
        <el-pagination
          :page-size="pageSize"
          :current-page.sync="currentPage"
          :total="total"
          background
          layout="total, prev, pager, next"
          @prev-click="currentPage--"
          @next-click="currentPage++"
          @current-change="getTableList(false)"
        />
      </div>
    </div>
    <el-dialog
      :title="viewTitle"
      :visible.sync="viewDialog"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="view"
        :model="viewForm"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="name" label="角色名称">
              <el-input
                v-model="viewForm.name"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="permission" label="权限(key)">
              <el-input
                v-model="viewForm.permission"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item prop="levelStr" label="角色级别">
              <el-input
                v-model="viewForm.levelStr"
                readonly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="dataScope" label="角色领域">
              <el-input
                v-model="viewForm.dataScope"
                readonly
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="remark" label="角色描述">
          <el-input
            v-model="viewForm.remark"
            readonly
            type="textarea"
          />
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="handleTitle"
      :visible.sync="handleDialog"
      width="40%"
      :close-on-click-modal="false"
    >
      <handle
        v-if="handleDialog"
        :action="action"
        :form-data="handleForm"
        :level="level"
        :level-list="levelList"
        :menu-list="menuList"
        @closeDialog="closeHandleDialog"
      />
    </el-dialog>
  </div>
</template>

<script>
import mixins, { commonMixin } from '@/utils/mixins'
import handle from './handle'
import * as getApi from '@/api/roles'
import { queryMenusList } from '@/api/menus'
function validSelect(data, msg) {
  if (!data) {
    this.$message({
      message: msg,
      type: 'warning'
    })
  }
  return !!data
}
export default {
  components: {
    handle
  },
  mixins: [mixins, commonMixin],
  data() {
    return {
      btnLists: [
        {
          funCode: 'add',
          color: 'primary',
          icon: 'plus',
          funName: '新增角色'
        },
        {
          funCode: 'edit',
          color: 'danger',
          icon: 'edit',
          funName: '修改角色'
        },
        {
          funCode: 'del',
          color: 'warning',
          icon: 'delete',
          funName: '删除角色'
        }
      ],
      searchForm: { // 搜索表单
        name: ''
      },
      mainLoading: false,
      tableLoading: false,
      tableData: [],
      pageSize: 10,
      currentPage: 1,
      total: 0,
      viewForm: {}, // 查看详情表单
      viewDialog: false, // 查看详情弹窗
      viewTitle: '查看详情',
      handleDialog: false,
      handleForm: {},
      handleTitle: '新增角色',
      action: 'add',
      downloadOptions: { // 下载文件参数
        url: '/api/roles/download',
        fileName: '角色数据.xlsx'
      },
      level: '',
      levelList: [
        { id: 1, name: '一级' },
        { id: 2, name: '二级' },
        { id: 3, name: '三级' }
      ],
      menuList: []
    }
  },
  created() {
    Promise.allSettled([getApi.queryRolesLevel(), queryMenusList(), this.getTableList(true)]).then(res => {
      this.level = res[0].value.level
      this.menuList = res[1].value.content
    }).catch(err => {
      console.log(err)
    })
  },
  methods: {
    getTableList(noLoading) {
      if (!noLoading) {
        this.tableLoading = true
      }
      const params = {
        size: this.pageSize,
        page: this.currentPage - 1,
        ...this.searchForm
      }
      return getApi.queryRolesList(params).then(res => {
        if (res && res.content) {
          const gradeObj = {
            1: '一级',
            2: '二级',
            3: '三级'
          }
          this.tableData = res.content.map(role => {
            role.levelStr = gradeObj[role.level]
            return role
          })
          this.total = res.totalElements
          this.currentSelect = ''
          return
        }
        throw new Error('暂无数据')
      }).catch(err => {
        this.$message({
          message: err || '获取表格数据失败!',
          type: 'error'
        })
        this.tableData = []
        this.total = this.tableData.length
      }).finally(() => {
        this.tableLoading = false
      })
    },
    handle(name, code) {
      if (name === 'left') {
        code && this[`${name}${code}`]()
        return
      }
      name && this[name](name)
    },
    add() {
      this.action = 'add'
      this.handleDialog = true
    },
    edit() {
      const valid = validSelect.call(this, this.currentSelect, '请先选择一条要修改的角色')
      if (!valid) return
      this.handleForm = this.currentSelect
      this.action = 'edit'
      this.handleDialog = true
    },
    del() {
      const valid = validSelect.call(this, this.currentSelect, '请先选择一条要删除的角色')
      if (!valid) return
      this.$confirm('确定要删除吗?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.mainLoading = true
        getApi.delRoles([this.currentSelect.id]).then(res => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
        }).catch(() => {
          this.$message({
            message: '删除失败',
            type: 'error'
          })
        }).finally(() => {
          this.mainLoading = false
          this.currentPage = 1
          this.getTableList(false)
        })
      }).catch(() => {})
    },
    // 查看详情
    viewDetail(row) {
      this.viewForm = row
      this.viewTitle = '查看角色详情'
      this.viewDialog = true
    },
    // 表格内某一行被点击时触发
    handleClickRow(row) {
      // console.log(row)
      this.tableData.forEach((item, index) => {
        if (item.id !== row.id) {
          item.checked = false
        }
      })
      if (!row.checked) {
        row.checked = true
        this.$refs.singleTable.setCurrentRow(row)
        this.currentSelect = row
      } else {
        row.checked = false
        this.$refs.singleTable.setCurrentRow()
        this.currentSelect = ''
      }
    },
    // 点击表格中的单选按钮
    handleReturn(row) {
      // console.log('点击表格中的单选按钮', row)
      this.tableData.forEach((item, index) => {
        if (item.id !== row.id) {
          item.checked = false
        }
      })
      if (row.checked) {
        this.$refs.singleTable.setCurrentRow()
        this.currentSelect = ''
      } else {
        this.$refs.singleTable.setCurrentRow(row)
        this.currentSelect = row
      }
    },
    // 表格序号编号
    indexMethod(indexs) {
      return (indexs + 1) + this.pageSize * (this.currentPage - 1)
    },
    // 重置搜索表单
    resetForm() {
      this.currentPage = 1
      this.$refs.search.resetFields()
    },
    closeHandleDialog(isRefresh) {
      this.handleDialog = false
      isRefresh && this.getTableList(false)
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
